package com.ctgu.demo03.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctgu.demo03.entity.ProductsEntity;
import com.ctgu.demo03.service.ProductsService;
import com.ctgu.demo03.mapper.ProductsMapper;
import com.ctgu.demo03.utils.ApiResult;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;

/**
* @author Alex2
* @description 针对表【t_products】的数据库操作Service实现
* @createDate 2025-03-11 21:41:45
*/
@Service
public class ProductsServiceImpl extends ServiceImpl<ProductsMapper, ProductsEntity>
    implements ProductsService {

    /**
     * @Author: Alex
     * @Description: 插入产品
     */
    @Override
    public ApiResult insertProducts(String name, Integer stock) {
        ProductsEntity products = lambdaQuery().eq(ProductsEntity::getName, name).one();
        if (products != null) {
            return ApiResult.error("该商品已存在");
        }
        ProductsEntity productsEntity = new ProductsEntity(null, name, stock, null);
        boolean save = save(productsEntity);
        if (!save) {
            return ApiResult.error("插入商品失败");
        }
        return ApiResult.success("插入商品成功");
    }

    /**
     * @Author: Alex
     * @Description: 版本号实现乐观锁
     */
    @Override
    public ApiResult updateProductPrice(Integer id) {
        ProductsEntity products = lambdaQuery().eq(ProductsEntity::getId, id).one();
        if (products == null || products.getStock() <= 0) {
            return ApiResult.error("库存不足");
        }
        ProductsService productsServiceProxy = (ProductsService) AopContext.currentProxy();
        boolean update = productsServiceProxy.updateProductPriceTransactional(id, products.getVersion());
        if (!update) {
            return ApiResult.error("更新失败，数据已被修改，请重试");
        } else {
            return ApiResult.success("更新成功");
        }
    }

    @Transactional
    public boolean updateProductPriceTransactional(Integer id, Integer version) {
        return lambdaUpdate()
                .eq(ProductsEntity::getId, id)
                .eq(ProductsEntity::getVersion, version)
                .setSql("stock = stock -1")
                .set(ProductsEntity::getVersion, version + 1)
                .update();
    }
}